using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class GamePanel : UIPanel
{

    private TileBoard       board;
    private TextMeshProUGUI scoreText;
    private TextMeshProUGUI hiscoreText;

    private Button    btnHome;
    private Button    newGame;
    public  Transform targetTrans;
    
    public  int                 score { get; private set; } = 0;
    
    private void Awake()
    {
        board         = FindObjectOfType<TileBoard>();
        scoreText     = transform.Find("Score/Value").GetComponent<TextMeshProUGUI>();
        hiscoreText   = transform.Find("Best/Value").GetComponent<TextMeshProUGUI>();
        btnHome       = transform.Find("ReturnButton").GetComponent<Button>();
        newGame       = transform.Find("NewGame").GetComponent<Button>();
        
        
        btnHome.onClick.AddListener(OnClickHome);
        newGame.onClick.AddListener(OnRestartClick);
        
        
    }


    //游戏刚开始默认生成两个2
    private void Start()
    {
        NewGame();
        
    }

    public void NewGame()
    {
       
        SetScore(0);
        hiscoreText.text = LoadHiscore().ToString();
        
        UIManager.Instance.ClosePanel<GameOverPanel>();
        
        board.ClearTile();
        board.CreateTile();
        board.CreateTile();
        board.enabled = true;
    }

    public void OnRestartClick()
    {
        NewGame();
        if (PlayerPrefs.GetInt(Const.NOVICE)==0)
            GuidancePanel._instance.NextStep(Const.ClickRestart);
    }

    public void GameOver()
    {
        board.enabled = false;
        //保存记录
        LocalConfig.intance.AddRecord(DateTime.Now.ToString("yyyy-MM-dd HH:mm"),score);
        
        UIManager.Instance.OpenPanel<GameOverPanel>();
    }

    public void IncreaseScore(int points)
    {
        SetScore(score+points);
    }

    private void SetScore(int score)
    {
        this.score = score;
        scoreText.text = score.ToString();
        SaveHiscore();
    }

    private void SaveHiscore()
    {
        int hiscore = LoadHiscore();
        if(score > hiscore)
            PlayerPrefs.SetInt(Const.HISCORE,score);
    }

    private int LoadHiscore()
    {
        return PlayerPrefs.GetInt(Const.HISCORE, 0);
    }

    void OnClickHome()
    {
        Hide();
        UIManager.Instance.ClosePanel<GameOverPanel>();
        UIManager.Instance.OpenPanel<MenuPanel>();
        if (PlayerPrefs.GetInt(Const.NOVICE)==0)
            GuidancePanel._instance.NextStep(Const.ClickBack);
    }
}
